package com.heima.search.kafkalistener;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * @author Psycho
 * @create 2022-05-01-22:53
 */
@Component
@Slf4j
public class IndexListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @KafkaListener(topics = "search-topic")
    public void indexListener(String message) {
        if(StringUtils.isNotBlank(message)){
            log.info("SyncArticleListener,message={}",message);
            //建立新增索引的请求
            IndexRequest request = new IndexRequest("")
                    .id(JSON.parseObject(message, Map.class).get("id").toString())
                    .source(message, XContentType.JSON);
            try {
                restHighLevelClient.index(request, RequestOptions.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("sync es error={}",e);
            }
        }
    }
}
